<template>
  <div id="teacherNumByGenderPage">
    <div ref="chartRef" style="width: 800px; height: 600px;"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import { getNumByGenderUsingGet } from '@/api/teacherController.ts'
import { message } from 'ant-design-vue'

const chartRef = ref(null)
let chartInstance = null

const genderData = ref()

const renderChart = () => {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }

  const option = {
    title: {
      text: '男女教师人数比例',
      left: 'center'
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '人数',
        type: 'pie',
        radius: '50%',
        data: [
          { value: genderData.value['1'] ?? 0, name: '男' },
          { value: genderData.value['0'] ?? 0, name: '女' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  chartInstance.setOption(option)
}

onMounted(async () => {
  const res = await getNumByGenderUsingGet()
  if (res.data.code === 0 && res.data.data) {
    genderData.value = res.data.data
  } else {
    message.error("获取数据失败" + res.data.message)
  }
  // 监听窗口大小变化，防止图表不自适应
  window.addEventListener('resize', () => {
    chartInstance.resize()
  })
})

// 如果genderData是接口动态获取的，推荐监听它重新渲染
watch(genderData, () => {
  renderChart()
})
</script>

<style scoped>
#teacherNumByGenderPage {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
